package com.example.net.update

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.example.baseutils.*
import com.example.baseutils.Constance.DETECT_PIC_ROOT_DIR
import com.example.baseutils.Constance.SAVE_VIDE_DIR
import com.example.net.http.RetrofitCreator
import com.example.net.http.request.RankUploadRequest
import org.litepal.LitePal
import java.util.concurrent.Executors
import java.util.concurrent.LinkedBlockingQueue

class PushDataService : Service() {

    private val thredPool = Executors.newFixedThreadPool(2)

    companion object {
        var running = false
        private const val TAG = "PushDataService"
        val upRankQueue = LinkedBlockingQueue<RankUploadRequest>()
        val carId = ""
        val gameId = ""
        public fun addQueue(recordInfo: String): Boolean {
            "添加并存储数据 $recordInfo".log(TAG)
            val data = RankUploadRequest(recordInfo, System.currentTimeMillis(), gameId, carId)
            return upRankQueue.offer(data)
        }
    }

    override fun onBind(intent: Intent): IBinder {
        TODO()
    }

    override fun onCreate() {
        super.onCreate()
        if (running)
            return
        running = true
        pushData()
    }


    private fun pushData() {
        thredPool.execute {
            while (running) {
                "阻塞上报数据".log(TAG)
                val localRecord = upRankQueue.take()
                if (!NetUtil.isNetworkConnected()) {
                    "网络不可用，2秒后重试".log(TAG, LogUtils.LogLevel.E)
                    TimeUtil.delayMs(2 * 1000)
                    upRankQueue.offer(localRecord)
                    continue
                }
                //阻塞取出数据
                var upState: Boolean=false
                do {
//                    upState = RetrofitCreator.uploadRank(localRecord)?.success ?: false
                    if (!upState) {
                        "上传数据失败 5s 后重试".log(TAG)
                        TimeUtil.delayMs(2 * 1000L)
                    }
                } while (!upState)

                "上传成功 $localRecord".log(TAG)
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        running = false
        if (thredPool.isShutdown) {
            thredPool.shutdownNow()
        }

    }
}
